package com.tro.common.util.file;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUtils {
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	public static List<Map<String,String>> uploads(MultipartFile[] files, String destDir,String basePath) throws Exception {
		List<Map<String,String>> result=new ArrayList<>();
		Map<String,String> siglnFile=new HashMap<>();
		if(StringUtils.isBlank(destDir)){
			destDir = "/static/picture";
		}
		File dir = new File(basePath+destDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
        try {
         // String[]  fileNames = new String[files.length];
            int index = 0;
            //上传文件过程
            for (MultipartFile file : files) {             
            	siglnFile=new HashMap<>();
                String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                siglnFile.put("uploadName", file.getOriginalFilename());
                siglnFile.put("fileSize", getFileSize(file.getSize()));
                File destFile = new File(basePath + destDir);
                if (!destFile.exists()) {
                    destFile.mkdirs();
                }
                String fileNameNew = getFileNameNew() + "." + suffix;//
                File f = new File(destFile.getAbsoluteFile() + File.separator + fileNameNew);
                siglnFile.put("fileName", fileNameNew);
                
                
                //如果当前文件已经存在了，就跳过。
                if(f.exists()){
                    continue;
                }
                
                file.transferTo(f);
                f.createNewFile();
                //fileNames[index++] = basePath + destDir + fileNameNew;
                siglnFile.put("fileUrl", destDir +"/"+ fileNameNew);
                siglnFile.put("suffix", suffix);
               
                result.add(siglnFile);
            }
        } catch (Exception e) {
            throw e;
        }
        return result;
    }
	
	private static String getFileNameNew() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return fmt.format(new Date());
    }
	
	private static String getFileSize(long size){
		java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.0"); 
        Double KB=1024D;
        Double MB=1048576D;
        Double GB=1073741824D;
		if(size<MB){
			return df.format(size/KB)+"KB";
		}else if(size<GB){
			return df.format(size/MB)+"M";
		}else{
			return df.format(size/GB)+"G";
		}
		
	}
	
	
}
